<?php
/**
 * Servizio di autocomplete per il browser delle costruzioni/materiali
 */
Zend_Loader::loadClass("Application_Ajax_Server_Function");
class BrowseAll extends Application_Ajax_Server_Function
{
	const BROWSE_MIN_LENGTH = 3;
	const BROWSE_FIELD_ID = "id";
	const BROWSE_FIELD_NAME = "name";
	
	public function call() {
		$this->_params['term'] = '%';
		if (empty($this->_params['id_field'])) {
			$this->_params['id_field'] = self::BROWSE_FIELD_ID;
		}
		if (empty($this->_params['name_field'])) {
			$this->_params['name_field'] = self::BROWSE_FIELD_NAME;
		}
		return $this->_browse();
	}

	private function _browse() {
		$dbAdapter = Zend_Db_Table::getDefaultAdapter();

		$sql = sprintf("
				SELECT `%1\$s`, `%2\$s` FROM `%3\$s`
				WHERE `%2\$s` like '%%%4\$s%%'",
				mysql_escape_string($this->_params['id_field']),
				mysql_escape_string($this->_params['name_field']),
				mysql_escape_string($this->_params['domain']),
				mysql_escape_string($this->_params['term'])
		);

		try {
			$result = $dbAdapter->fetchPairs($sql);
		} catch (Exception $e) {
			return null;
		}
		return $result;
	}
}
